package com.zhongxi.guoyuan.view.play;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.RedBagResult;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.entity.gift.ShareResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.NewTipsActivity;
import com.zhongxi.guoyuan.view.personalCenter.BoxActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.redpacket.LuckyDrawView;

import org.json.JSONObject;

public class RedPacketActivity extends BaseActivity {

    private LuckyDrawView luckDrawView;
    private TextView tvChange;
    private TextView tvCash;
    private TextView tvDetail;
    private View popupWindow_view;
    private PopupWindow popupWindow;
    private SHARE_MEDIA platform;
    private String type;
    private ImageView ivTips;
    private UMShareAPI mShareAPI;
    private boolean flag;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_red_packet);
        luckDrawView = (LuckyDrawView) findViewById(R.id.luck_draw);
        tvChange = (TextView) findViewById(R.id.tvChange);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvDetail = (TextView) findViewById(R.id.tvDetail);
        ivTips = (ImageView) findViewById(R.id.ivTips);
        initTitle();
        tvTitle.setText("红包搜一搜");
        mShareAPI = UMShareAPI.get(this);
    }

    @Override
    protected void initData() {
        super.initData();
        type = "video";
        getServer(Url.SPONSORS_VIDEO, null, "", false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if("video".equals(type)){
                RedBagResult result = gson.fromJson(response, RedBagResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                float money = Float.parseFloat(MyApplication.getInstance().parseSecutiryKey(result.getBonusamount()));
                String url = Url.IMG_URL + result.getVediouri();
                String urlId = result.getVid();
                luckDrawView.setUrl(url, urlId, money);
                tvChange.setText("今日您还有 "+result.getResidualCount()+" 次抽奖机会");
                tvCash.setText("今日累积获得现金 "+result.getTotalFee()+" 元");
            }else if("share".equals(type)){
                ShareResult result = gson.fromJson(response, ShareResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow(result);
                }
            }else if("shareget".equals(type)){
                ShareBeautifulResult result = gson.fromJson(response, ShareBeautifulResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showPopupWindow(result.getNum(), "分享");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showPopupWindow(String num, String str) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvTips.setText("成功分享获得"+num+"美币");
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
    }

    private void showMyDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_share_sure, null);
        final Dialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        TextView tvShare = (TextView) view.findViewById(R.id.tvShare);
        TextView tvQuit = (TextView) view.findViewById(R.id.tvQuit);
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                type = "share";
                String str = "&sharetype=2";
                getServer(Url.APPLY_SHARE, null, str, false, null, "get");
            }
        });
    }

    /**
     * 弹出分享界面
     * @param result
     */
    private void initPopuWindow(final ShareResult result) {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(tvDetail, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
//        LinearLayout ll_microblog = (LinearLayout) popupWindow_view.findViewById(R.id.ll_microblog);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                new ShareAction(RedPacketActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("美容何必再花钱！消费多少返多少=免费美容！")
                        .withText("手机里装一个自己的美容院，天天“摇钱树+搜红包”消费返银币=实现免费美容，下载即送大礼包！").withTargetUrl(Url.BASE_URL+"/share/welfare/show?sharekey="+result.getSharekey())
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
            type = "shareget";
            getServer(Url.SHARE, null, "", false, null, "get");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        }
        if(result.getCode() == 1001){
            showShortToast("用户未登录，请先登录");
            if(!flag){
                Intent intent = new Intent (context, LoginActivity.class);
                startActivityForResult(intent, 300);
            }else{
                finish();
            }
        }else if(result.getCode() == 1101){
            showShortToast("红包日次数已超限");
            try{
                JSONObject obj = new JSONObject(response);
                String residualCount = obj.getString("residualCount");
                String totalFee = obj.getString("totalFee");
                tvChange.setText("今日您还有 "+residualCount+" 次抽奖机会");
                tvCash.setText("今日累积获得现金 "+totalFee+" 元");
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if(result.getCode() == 1004){
            showShortToast("红包服务暂不可用");
        }else if(result.getCode() == 1102){
            showShortToast("暂无视频， 无法正常领取红包");
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                luckDrawView.onDestroyed();
                finish();
            }
        });
        //查看详情
        tvDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BoxActivity.class);
                intent.putExtra("index", 2);
                startActivity(intent);
            }
        });
        ivTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(NewTipsActivity.class);
            }
        });
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(luckDrawView!=null){
            luckDrawView.onDestroyed();
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode ==300 || requestCode == 500){   //播放完视频 ,从新获取数据
            type = "video";
            flag = true;
            getServer(Url.SPONSORS_VIDEO, null, "", false, null, "get");
            try{
                String flag = data.getExtras().getString("status");
                if(null!=flag&&!"".equals(flag)&&"1".equals(flag)){
                    showMyDialog();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        }
    }
}
